import { useState, useEffect, useContext } from 'react';
import { NavBar, List, Button, InfiniteScroll, Toast, Dialog } from 'antd-mobile';
import { useHistory } from 'react-router-dom';
import { DeleteOutlined } from '@ant-design/icons';

import AvatarImage from '../../../components/AvatarImage';
import { MySdkStoreContext } from '../../../context';
import { NEW_APPLICATION_STORAGE_KEY } from '../../../constants';

import { NewFriendApplyStatus } from './config';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [newApplicationList, setNewApplicationList] = useState([]);
  const [pagination, setPagination] = useState({});

  const getNewApplication = async (pageIndex = 1) => {
    const { rows, totalPage } = await mySdkStore.sdk.queryGroupJoinApplyList({ pageIndex });
    setNewApplicationList(pageIndex === 1 ? rows : [...rows, ...newApplicationList]);
    setPagination({ pageIndex, totalPage });
  }

  useEffect(() => {
    getNewApplication(1);
  }, []);

  useEffect(() => {
    const hasReadNewApplicationStr = localStorage.getItem(NEW_APPLICATION_STORAGE_KEY);
    let newApplicationObj = { hasReadNewGroupMemberApplication: true };
    if (hasReadNewApplicationStr) {
      try {
        const hasReadNewApplicationObj = JSON.parse(hasReadNewApplicationStr);
        newApplicationObj = {...hasReadNewApplicationObj, hasReadNewGroupMemberApplication: true };
      } catch {}
    }
    localStorage.setItem(NEW_APPLICATION_STORAGE_KEY, JSON.stringify(newApplicationObj));
  }, []);

  const getNextData = async () => {
    await getNewApplication(pagination.pageIndex + 1);
  }

  const handlePassApply = async (applyId) => {
    const action = mySdkStore.sdk.ImEnum?.GroupJoinApplyActionEnum?.AGREE;
    const res = await mySdkStore.sdk.updateGroupJoinApplyInfo({ applyId, action });
    if (res?.errorMessage) {
      Toast.show(res?.errorMessage);
      return;
    }
    getNewApplication(1);
  }

  const handleRefuse = async (applyId) => {
    const action = mySdkStore.sdk.ImEnum?.GroupJoinApplyActionEnum?.REJECT;
    const res = await mySdkStore.sdk.updateGroupJoinApplyInfo({ applyId, action });
    if (res?.errorMessage) {
      Toast.show(res?.errorMessage);
      return;
    }
    getNewApplication(1);
  }

  const handleClearApply = () => {
    Dialog.confirm({
      content: '请确认清空入群申请？',
      onConfirm: async () => {
        const res = await mySdkStore.sdk.clearMyGroupJoinApply();
        if (res?.errorMessage) {
          Toast.show(res?.errorMessage);
          return;
        }
        getNewApplication(1);
      }
    })
  }

  const getExtra = (status: number | string, applyInfo) => {
    switch(status) {
      case NewFriendApplyStatus.WAITING:
        return <>
          <Button size="mini" style={{ marginRight: 8 }} onClick={() => handleRefuse(applyInfo.id)}>拒绝</Button>
          <Button size="mini" color="primary" onClick={() => handlePassApply(applyInfo.id)}>同意</Button>
        </>
      case NewFriendApplyStatus.PASSED:
        return '已同意';
      case NewFriendApplyStatus.REFUSED:
        return '已拒绝';
    }
  }

  return (<div className="newFriendListPage">
      <NavBar
        onBack={() => history.goBack()}
        style={{ background: '#fff', border: 'none' }}
        right={ newApplicationList.length ? <DeleteOutlined onClick={handleClearApply} /> : null}>
        入群申请
      </NavBar>
      <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0, marginTop: 12 }}>
        { newApplicationList.map((item) =>
          <List.Item
            key={item.id}
            prefix={<AvatarImage
              nickName={item.nickName}
              userName={item.userName}
              userId={item.invitedUserId}
              style={{ borderRadius: '8px' }}
              src={item.avatarUrl}
              width={42}
              height={42}
              fit='fill' />}
            description={<div className="userId">ID: {item.invitedUserId}</div>}
            extra={getExtra(item.status, item)}
            >
            <div className="userName">{ item.userName }</div>
          </List.Item>
      )}
    </List>
    <InfiniteScroll loadMore={getNextData} hasMore={pagination.pageIndex < pagination.totalPage} />
  </div>)
}